#include "GraphNode.h"
#include "resources.h"

#include "../MeasurementObject.h"

#include "MOConnectionSelector.h"

#include <QLabel>
#include <QPushButton>
#include <QDialog>

namespace ui {

GraphNode::GraphNode(QWidget* _parent): BaseUI(), isTempSet(false) {
    parent = _parent;
}

GraphNode::~GraphNode() {
    if(formWidget)
        formWidget->close();
}

bool GraphNode::setup() {
    if(!BaseUI::setup(UI_GRAPH_NODE))
        return false;

    QPushButton *btnInput = formWidget->findChild<QPushButton*>("btnInput");
    QPushButton *btnOutput = formWidget->findChild<QPushButton*>("btnOutput");

    QObject::connect(btnInput, SIGNAL(clicked()), this, SLOT(onInput()));
    QObject::connect(btnOutput, SIGNAL(clicked()), this, SLOT(onOutput()));

    return true;
}

void GraphNode::setName(QString name) {
    QLabel *lblName = formWidget->findChild<QLabel*>("lblName");
    lblName->setText(name);
}

void GraphNode::setType(QString type) {
    QLabel *lblType = formWidget->findChild<QLabel*>("lblType");
    lblType->setText(type);

    std::string style;

    if(type == MO_CATEGORY_DATA_SOURCE) {
        style = COLOR_DATA_SOURCE;
    } else if(type == MO_CATEGORY_DATA_PROCESSOR) {
        style = COLOR_DATA_PROC;
    } else {
        style = COLOR_VIZUALIZATION;
    }

    lblType->setStyleSheet(QString::fromStdString(style));
}

void GraphNode::setHasInput(bool t) {
    QPushButton *btnInput = formWidget->findChild<QPushButton*>("btnInput");
    btnInput->setEnabled(t);
}

void GraphNode::setHasOutput(bool t) {
    QPushButton *btnOutput = formWidget->findChild<QPushButton*>("btnOutput");
    btnOutput->setEnabled(t);
}

void GraphNode::setMeasIndex(unsigned short index) {
    measIndex = index;
}

unsigned short GraphNode::getMeasIndex() {
    return measIndex;
}

void GraphNode::setTempPos(int x, int y) {
    tempPos.setX(x);
    tempPos.setY(y);
}

QPoint *GraphNode::getTempPos() {
    return &tempPos;
}

int GraphNode::getTempX() {
    return tempPos.x();
}

int GraphNode::getTempY() {
    return tempPos.y();
}

void GraphNode::setBaseLink(core::WeakMOPtr ptr) {
    baseLink = ptr;
}

core::WeakMOPtr GraphNode::getBaseLink() {
    return baseLink;
}

void GraphNode::onInput() {
    core::SharedMOPtr p = baseLink.lock();

    if(p) {
        MOConnectionSelector connSelector(parent, p);
        if(!connSelector.setup()) {
            core::Logger::getInstance().add(core::Error, L"Error opening MOConnectionSelector dialog");
            return;
        }
        QDialog *diag = static_cast<QDialog*>(connSelector.getWidget());
        diag->exec();
    }
}

void GraphNode::onOutput() {
    std::cerr << "ON OUTPUT()";
}

}
